/**
 * 音频管理器 - 处理音频播放、同步和可视化
 */

// 导入音频上下文单例
import audioContextSingleton from './core/audio-context-singleton.js';
export class AudioManager {
    constructor(options = {}) {
        this.options = {
            volume: 0.8,
            enableVisualization: true,
            enableSubtitles: true,
            autoPlay: true,
            crossfade: true,
            enableLipSync: true,
            ...options
        };
        
        this.currentAudio = null;
        this.audioQueue = [];
        this.isPlaying = false;
        this.isPaused = false;
        this.volume = this.options.volume;
        
        // 音频可视化
        this.audioContext = null;
        this.analyser = null;
        this.dataArray = null;
        this.source = null;
        
        // 唇语同步
        this.lipSyncManager = null;
        this.currentText = '';
        this.audioDuration = 0;
        
        // 回调函数
        this.callbacks = {
            onPlay: null,
            onPause: null,
            onStop: null,
            onEnd: null,
            onProgress: null,
            onTimeupdate: null,
            onVolumeChange: null,
            onVisualizationData: null,
            onLipSyncData: null
        };
        
        this.init();
    }
    
    init() {
        // 不在初始化时创建音频上下文，等到需要时再创建
        this.setupEventListeners();
    }
    
    setupAudioContext() {
        try {
            // 延迟创建音频上下文，直到需要时再创建
            if (!this.audioContext) {
                // 使用音频上下文单例
                this.audioContext = audioContextSingleton.getContext();
                this.analyser = this.audioContext.createAnalyser();
                this.analyser.fftSize = 256;
                
                const bufferLength = this.analyser.frequencyBinCount;
                this.dataArray = new Uint8Array(bufferLength);
                
                // 连接到输出
                this.analyser.connect(this.audioContext.destination);
            }
        } catch (error) {
            console.warn('音频上下文初始化失败:', error);
        }
    }

    async ensureAudioContext() {
        if (!this.audioContext) {
            this.setupAudioContext();
        }
        
        // 确保音频上下文已启动
        try {
            await audioContextSingleton.resume();
            console.log('音频上下文已恢复');
        } catch (error) {
            console.warn('无法恢复音频上下文:', error);
        }
    }
    
    setupEventListeners() {
        // 页面可见性变化
        document.addEventListener('visibilitychange', () => {
            if (document.hidden && this.isPlaying) {
                this.pause();
            }
        });
        
        // 页面卸载时清理
        window.addEventListener('beforeunload', () => {
            this.cleanup();
        });
    }
    
    /**
     * 播放音频
     * @param {string|Blob} audioSource - 音频URL或Blob对象
     * @param {Object} options - 播放选项
     */
    async playAudio(audioSource, options = {}) {
        try {
            // 停止当前播放
            if (this.currentAudio) {
                this.stop();
            }

            // 确保音频上下文已启动
            await this.ensureAudioContext();
            
            // 创建音频元素
            const audio = new Audio();
            
            if (audioSource instanceof Blob) {
                audio.src = URL.createObjectURL(audioSource);
            } else {
                audio.src = audioSource;
            }
            
            audio.volume = this.volume;
            audio.crossOrigin = 'anonymous';
            
            // 保存文本和时长信息
            this.currentText = options.text || '';
            this.audioDuration = options.duration || 0;
            
            // 设置音频事件
            this.setupAudioEvents(audio, options);
            
            // 连接到音频上下文
            if (this.audioContext && this.analyser) {
                this.connectToAnalyser(audio);
            }
            
            // 保存当前音频引用
            this.currentAudio = audio;
            
            // 等待音频加载完成后播放
            return new Promise((resolve, reject) => {
                audio.addEventListener('canplaythrough', async () => {
                    try {
                        // 初始化唇语同步
                        if (this.options.enableLipSync && this.currentText) {
                            await this.initLipSync(audio, this.currentText, this.audioDuration);
                        }
                        
                        // 播放音频
                        await audio.play();
                        console.log('音频开始播放');
                        
                        // 更新状态
                        this.isPlaying = true;
                        this.isPaused = false;
                        
                        // 开始可视化
                        if (this.options.enableVisualization) {
                            this.startVisualization();
                        }
                        
                        // 开始唇语同步
                        if (this.lipSyncManager) {
                            this.lipSyncManager.startPlayback();
                        }
                        
                        this.triggerCallback('onPlay', { audio, options });
                        resolve(audio);
                    } catch (error) {
                        console.error('音频播放失败:', error);
                        reject(error);
                    }
                }, { once: true });
                
                audio.addEventListener('error', (error) => {
                    console.error('音频加载失败:', error);
                    reject(error);
                }, { once: true });
                
                // 开始加载音频
                audio.load();
            });
            
        } catch (error) {
            console.error('播放音频时出错:', error);
            this.triggerCallback('onError', error);
            throw error;
        }
    }
    
    setupAudioEvents(audio, options) {
        audio.addEventListener('loadstart', () => {
            console.log('开始加载音频');
        });
        
        audio.addEventListener('canplay', () => {
            console.log('音频可以播放');
        });
        
        audio.addEventListener('timeupdate', () => {
            if (this.isPlaying) {
                const progress = {
                    currentTime: audio.currentTime,
                    duration: audio.duration,
                    percentage: (audio.currentTime / audio.duration) * 100
                };
                this.triggerCallback('onProgress', progress);
                // 同时触发timeupdate事件，供字幕同步使用
                this.triggerCallback('timeupdate', progress);
            }
        });
        
        audio.addEventListener('ended', () => {
            this.isPlaying = false;
            this.isPaused = false;
            this.triggerCallback('onEnd', { audio });
            
            // 播放队列中的下一个
            this.playNext();
        });
        
        audio.addEventListener('error', (e) => {
            console.error('音频播放错误:', e);
            this.isPlaying = false;
            this.isPaused = false;
        });
        
        audio.addEventListener('pause', () => {
            this.isPaused = true;
            this.triggerCallback('onPause', { audio });
        });
        
        audio.addEventListener('play', () => {
            this.isPaused = false;
            this.triggerCallback('onPlay', { audio });
        });
    }
    
    connectToAnalyser(audio) {
        try {
            // 检查是否已经为这个音频元素创建了source
            if (this.currentAudioElement === audio && this.source) {
                return; // 已经连接，无需重复创建
            }
            
            // 断开之前的连接
            if (this.source) {
                this.source.disconnect();
                this.source = null;
            }
            
            // 创建新的MediaElementSource
            this.source = this.audioContext.createMediaElementSource(audio);
            this.source.connect(this.analyser);
            this.source.connect(this.audioContext.destination); // 确保音频能够播放
            
            // 记录当前音频元素
            this.currentAudioElement = audio;
        } catch (error) {
            console.warn('连接音频分析器失败:', error);
            // 如果连接失败，确保音频仍能播放
            if (!audio.src) return;
            try {
                audio.connect && audio.connect(this.audioContext.destination);
            } catch (e) {
                // 忽略连接错误，音频仍可通过默认路径播放
            }
        }
    }
    
    startVisualization() {
        if (!this.analyser || !this.dataArray) return;
        
        const updateVisualization = () => {
            if (!this.isPlaying) return;
            
            this.analyser.getByteFrequencyData(this.dataArray);
            
            // 计算音频特征
            const features = this.calculateAudioFeatures(this.dataArray);
            
            this.triggerCallback('onVisualizationData', {
                frequencyData: this.dataArray,
                features
            });
            
            requestAnimationFrame(updateVisualization);
        };
        
        updateVisualization();
    }
    
    calculateAudioFeatures(dataArray) {
        let sum = 0;
        let max = 0;
        
        for (let i = 0; i < dataArray.length; i++) {
            sum += dataArray[i];
            max = Math.max(max, dataArray[i]);
        }
        
        const average = sum / dataArray.length;
        const energy = Math.sqrt(sum / dataArray.length);
        
        return {
            average,
            max,
            energy,
            volume: energy / 255,
            bass: this.getFrequencyRange(dataArray, 0, 10),
            mid: this.getFrequencyRange(dataArray, 10, 50),
            treble: this.getFrequencyRange(dataArray, 50, dataArray.length)
        };
    }
    
    getFrequencyRange(dataArray, start, end) {
        let sum = 0;
        const count = end - start;
        
        for (let i = start; i < end && i < dataArray.length; i++) {
            sum += dataArray[i];
        }
        
        return sum / count;
    }
    
    /**
     * 暂停播放
     */
    pause() {
        if (this.currentAudio && this.isPlaying) {
            this.currentAudio.pause();
            this.isPlaying = false;
            this.isPaused = true;
        }
    }
    
    /**
     * 恢复播放
     */
    resume() {
        if (this.currentAudio && this.isPaused) {
            this.currentAudio.play();
            this.isPlaying = true;
            this.isPaused = false;
        }
    }
    
    /**
     * 停止播放
     */
    stop() {
        if (this.currentAudio) {
            this.currentAudio.pause();
            this.currentAudio.currentTime = 0;
            
            // 清理URL对象
            if (this.currentAudio.src.startsWith('blob:')) {
                URL.revokeObjectURL(this.currentAudio.src);
            }
            
            this.currentAudio = null;
        }
        
        this.isPlaying = false;
        this.isPaused = false;
        
        // 停止唇语同步
        this.stopLipSync();
        
        this.triggerCallback('onStop');
    }
    
    /**
     * 设置音量
     * @param {number} volume - 音量值 (0-1)
     */
    setVolume(volume) {
        this.volume = Math.max(0, Math.min(1, volume));
        
        if (this.currentAudio) {
            this.currentAudio.volume = this.volume;
        }
        
        this.triggerCallback('onVolumeChange', this.volume);
    }
    
    /**
     * 获取当前音量
     */
    getVolume() {
        return this.volume;
    }
    
    /**
     * 跳转到指定时间
     * @param {number} time - 时间（秒）
     */
    seekTo(time) {
        if (this.currentAudio) {
            this.currentAudio.currentTime = time;
        }
    }
    
    /**
     * 获取播放进度
     */
    getProgress() {
        if (!this.currentAudio) return null;
        
        return {
            currentTime: this.currentAudio.currentTime,
            duration: this.currentAudio.duration,
            percentage: (this.currentAudio.currentTime / this.currentAudio.duration) * 100
        };
    }
    
    /**
     * 添加到播放队列
     * @param {string|Blob} audioSource - 音频源
     * @param {Object} options - 选项
     */
    addToQueue(audioSource, options = {}) {
        this.audioQueue.push({ audioSource, options });
    }
    
    /**
     * 播放队列中的下一个
     */
    async playNext() {
        if (this.audioQueue.length > 0) {
            const { audioSource, options } = this.audioQueue.shift();
            await this.playAudio(audioSource, options);
        }
    }
    
    /**
     * 清空播放队列
     */
    clearQueue() {
        this.audioQueue = [];
    }
    
    /**
     * 获取队列长度
     */
    getQueueLength() {
        return this.audioQueue.length;
    }
    
    /**
     * 设置回调函数
     * @param {string} event - 事件名称
     * @param {Function} callback - 回调函数
     */
    on(event, callback) {
        if (this.callbacks.hasOwnProperty(`on${event.charAt(0).toUpperCase() + event.slice(1)}`)) {
            this.callbacks[`on${event.charAt(0).toUpperCase() + event.slice(1)}`] = callback;
        }
    }
    
    /**
     * 移除回调函数
     * @param {string} event - 事件名称
     */
    off(event) {
        const callbackName = `on${event.charAt(0).toUpperCase() + event.slice(1)}`;
        if (this.callbacks.hasOwnProperty(callbackName)) {
            this.callbacks[callbackName] = null;
        }
    }
    
    /**
     * 触发回调函数
     * @param {string} callbackName - 回调名称
     * @param {*} data - 数据
     */
    triggerCallback(callbackName, data = null) {
        const callback = this.callbacks[callbackName];
        if (callback && typeof callback === 'function') {
            try {
                callback(data);
            } catch (error) {
                console.error(`回调函数 ${callbackName} 执行失败:`, error);
            }
        }
    }
    
    /**
     * 创建音频可视化效果
     * @param {HTMLCanvasElement} canvas - 画布元素
     */
    createVisualization(canvas) {
        if (!canvas || !this.analyser) return null;
        
        const ctx = canvas.getContext('2d');
        const width = canvas.width;
        const height = canvas.height;
        
        const draw = () => {
            if (!this.isPlaying) return;
            
            this.analyser.getByteFrequencyData(this.dataArray);
            
            ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
            ctx.fillRect(0, 0, width, height);
            
            const barWidth = width / this.dataArray.length;
            let x = 0;
            
            for (let i = 0; i < this.dataArray.length; i++) {
                const barHeight = (this.dataArray[i] / 255) * height;
                
                const r = barHeight + 25 * (i / this.dataArray.length);
                const g = 250 * (i / this.dataArray.length);
                const b = 50;
                
                ctx.fillStyle = `rgb(${r},${g},${b})`;
                ctx.fillRect(x, height - barHeight, barWidth, barHeight);
                
                x += barWidth + 1;
            }
            
            requestAnimationFrame(draw);
        };
        
        draw();
        return { canvas, ctx, draw };
    }
    
    /**
     * 音频淡入效果
     * @param {number} duration - 淡入时长（毫秒）
     */
    fadeIn(duration = 1000) {
        if (!this.currentAudio) return;
        
        const startVolume = 0;
        const endVolume = this.volume;
        const startTime = Date.now();
        
        this.currentAudio.volume = startVolume;
        
        const fade = () => {
            const elapsed = Date.now() - startTime;
            const progress = Math.min(elapsed / duration, 1);
            
            this.currentAudio.volume = startVolume + (endVolume - startVolume) * progress;
            
            if (progress < 1) {
                requestAnimationFrame(fade);
            }
        };
        
        fade();
    }
    
    /**
     * 音频淡出效果
     * @param {number} duration - 淡出时长（毫秒）
     */
    fadeOut(duration = 1000) {
        if (!this.currentAudio) return;
        
        const startVolume = this.currentAudio.volume;
        const endVolume = 0;
        const startTime = Date.now();
        
        const fade = () => {
            const elapsed = Date.now() - startTime;
            const progress = Math.min(elapsed / duration, 1);
            
            this.currentAudio.volume = startVolume + (endVolume - startVolume) * progress;
            
            if (progress < 1) {
                requestAnimationFrame(fade);
            } else {
                this.stop();
            }
        };
        
        fade();
    }
    
    /**
     * 初始化唇语同步
     * @param {HTMLAudioElement} audio - 音频元素
     * @param {string} text - 对应的文本
     * @param {number} duration - 音频时长
     */
    async initLipSync(audio, text, duration) {
        try {
            // 动态导入LipSyncManager
            const { LipSyncManager } = await import('./LipSyncManager.js');
            
            // 创建唇语同步管理器
            this.lipSyncManager = new LipSyncManager({
                sensitivity: 1.2,
                smoothing: 0.7
            });
            
            // 连接音频
            this.lipSyncManager.connectAudio(audio);
            
            // 分析文本生成音素序列
            const sequence = this.lipSyncManager.analyzeText(text, duration);
            console.log('生成音素序列:', sequence);
            
            // 设置唇语同步回调
            this.lipSyncManager.on('visemeChange', (viseme, intensity) => {
                this.triggerCallback('onLipSyncData', {
                    viseme,
                    intensity,
                    time: this.lipSyncManager.currentTime
                });
            });
            
            console.log('唇语同步初始化成功');
            
        } catch (error) {
            console.error('唇语同步初始化失败:', error);
        }
    }
    
    /**
     * 停止唇语同步
     */
    stopLipSync() {
        if (this.lipSyncManager) {
            this.lipSyncManager.stopPlayback();
        }
    }
    
    /**
     * 销毁唇语同步管理器
     */
    disposeLipSync() {
        if (this.lipSyncManager) {
            this.lipSyncManager.dispose();
            this.lipSyncManager = null;
        }
    }
    
    /**
     * 获取当前唇语同步数据
     * @returns {Object|null} 当前音素信息
     */
    getCurrentLipSyncData() {
        return this.lipSyncManager ? this.lipSyncManager.getCurrentViseme() : null;
    }
    
    /**
     * 获取音频信息
     */
    getAudioInfo() {
        if (!this.currentAudio) return null;
        
        return {
            src: this.currentAudio.src,
            duration: this.currentAudio.duration,
            currentTime: this.currentTime,
            volume: this.currentAudio.volume,
            paused: this.currentAudio.paused,
            ended: this.currentAudio.ended,
            readyState: this.currentAudio.readyState
        };
    }
    
    /**
     * 检查浏览器音频支持
     */
    static checkAudioSupport() {
        const audio = new Audio();
        const support = {
            mp3: audio.canPlayType('audio/mpeg') !== '',
            wav: audio.canPlayType('audio/wav') !== '',
            ogg: audio.canPlayType('audio/ogg') !== '',
            m4a: audio.canPlayType('audio/mp4') !== '',
            webAudioAPI: !!(window.AudioContext || window.webkitAudioContext)
        };
        
        return support;
    }
    
    /**
     * 清理资源
     */
    cleanup() {
        this.stop();
        this.clearQueue();
        
        if (this.source) {
            this.source.disconnect();
            this.source = null;
        }
        
        if (this.audioContext && this.audioContext.state !== 'closed') {
            this.audioContext.close();
        }
        
        // 清理所有回调
        Object.keys(this.callbacks).forEach(key => {
            this.callbacks[key] = null;
        });
    }
}